package com.sinosoft.hydra.um.services.component.dataCollect.readers;

import cn.com.sinux.spring.utils.FileUtils;
import com.sinosoft.hydra.logging.LogModules;
import com.sinosoft.hydra.um.constant.BaseConstant;
import com.sinosoft.hydra.um.domain.model.LabDataParser;
import com.sinosoft.hydra.um.services.component.dataCollect.DataParser;
import com.sinosoft.hydra.um.services.component.dataCollect.DataReader;
import com.sinosoft.hydra.um.services.component.dataCollect.DataResult;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * Created by Administrator on 2016/8/16.
 */
public class DatAndBmpReader implements DataReader {


    public DataResult read(List<String> paths, Date begin, Date end, DataParser parser, LabDataParser labDataParser) {
        DataResult result = new DataResult();
        for (String path : paths) {
            if (path.endsWith(".bmp")) {
                readBmp(new File(path), result);
            } else if (path.endsWith(".dat")) {
                try {
                    readDat(new File(path), begin, end, parser, result, labDataParser);
                } catch (IOException e) {
                    LoggerFactory.getLogger(LogModules.STD_LOGGER).error("文件解析失败，没有获取到数据{}", e.getMessage());
                    return null;
                }
            }
        }
        return result;
    }

    private void readBmp(File file, DataResult dataResult) {
        if (file.exists()) {
            dataResult.addLabel(file.getPath(), BaseConstant.LabelType.LABEL_TYPE_IMG);
        }
    }

    private void readDat(File file, Date begin, Date end, DataParser parser, DataResult dataResult, LabDataParser labDataParser) throws IOException {
        List<String> rows = FileUtils.readLines(file, labDataParser.getEncoding());
        List<String> titles;
        if (labDataParser.getTitleRowNum() == -1) {
            titles = parser.getTitles();
        } else {
            titles = Arrays.asList(rows.get(labDataParser.getTitleRowNum()).split(" "));
        }
        int last = labDataParser.getCellsNum() == -1 ? titles.size() : labDataParser.getCellsNum();
        dataResult.addTitles(titles, last, parser);
        for (int i = labDataParser.getStartRowNum(), l = rows.size(); i < l; i++) {
            List<String> cels = Arrays.asList(rows.get(i).split(" "));
            if (!parser.valid(cels)) {
                break;
            }
            dataResult.addData(parser.parse(cels, begin, end), last, parser);
        }
    }
}
